package billingServer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.ConnectException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 *
 * @author Group 95
 */
public class Server {

    public static void main(String[] args) {

        try {
            String name;
            if(args.length == 0) {
                name = "Billing";
            } else {
             
            name = args[0];   
            }
            BillingServerRMI engine = new BillingServerRMI();
            Registry registry = LocateRegistry.getRegistry(13249);
            try {
                registry.rebind(name, engine);
            } catch (ConnectException cex) {
                registry = LocateRegistry.createRegistry(13249);
                registry.bind(name, engine);
            }
            System.out.println("Billingserver bound");
            
            //!exit
            InputStreamReader inputStream = new InputStreamReader(System.in);
            BufferedReader brStdIn = new BufferedReader(inputStream);
            String strLine;
                while ((strLine = brStdIn.readLine()) != null) {
                    if (strLine.contentEquals("!exit")) {
                        System.out.println("Exit-command entered, stop BillingServer...");
                        engine.stop();
                        break;
                    }
                }
                UnicastRemoteObject.unexportObject(engine, true);                 
                //UnicastRemoteObject.unexportObject(registry, true);
                    brStdIn.close();
                    inputStream.close();
        } catch (Exception e) {
            System.err.println("Billingserver exception:");
            e.printStackTrace();
        }
    }
}
